<?php 

	session_start();
	if(!($_SESSION["username"])||($_SESSION["role"]!="TUT")){
		//not logged in or tutor
		header("location:index.php");
	}
	
	$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
	$objDB = mysql_select_db("Project 5.5");
	
	$students=$_POST['recipients'];
	$tutors = null;
	$emails=null;
	$i=0;
	//add emails for selected students
	if (isset($_POST['tutors'])&&$_POST['tutors']=='Yes') {
		foreach ($students as $s) {
			$sql="SELECT Email FROM users WHERE User_ID IN(SELECT Tutor FROM classes WHERE Class_ID IN (SELECT Class_ID FROM studentinfo WHERE User_ID='".$s."'))";
			$result=mysql_fetch_row(mysql_query($sql));
			if(!in_array($result[0],$emails)){
				$emails[$i]=$result[0];
				$i++;
			}
		}		
	}
	foreach ($students as $s) {
		
		$sql="SELECT Email FROM users WHERE User_ID=".$s.";";
		$result=mysql_fetch_row(mysql_query($sql));
		$emails[$i]=$result[0];
		$i++;
	};
	
	$recipients="";
	foreach ($emails as $e) {
		$recipients.=$e.", ";
		}
	$recipients = rtrim($recipients, ", ");
	
	$sql="SELECT Email FROM users WHERE Username='".$_SESSION['username']."';";
	$result=mysql_fetch_row(mysql_query($sql));
	$sender = "From: ".$result[0];
	
	
	$sql="SELECT Due_Date, Assessment_Name, Submission FROM assessment WHERE Assessment_ID='".$_POST['assessment'][0]."'";
	$result=mysql_fetch_row(mysql_query($sql));	
	$due=$result[0];
	
	//select message for related assignment and state
	$state=$_POST['state'];
	switch($state[0]){
		case "Late":
			$subject = $result[1]." Overdue";
			$message = "Dear Student,\n\nThe assessment item '".$result[1]."' was not submited by its due date (".$due.").\nPlease submit this assessment item via ".$result[2]." as soon as possible.\nThank you";
			break;
		case "Due":
			$subject = $result[1]." Due";
			$message = "Dear Student,\n\nThe assessment item '".$result[1]."' is due on the ".$due.".\nPlease submit this assessment item via ".$result[2]." by the due date.\nThank you";
			break;
		case "Marked":
			$subject = $result[1]." Marked";
			$message = "Dear Student,\n\nYour assessment item '".$result[1]."' has been marked.\nPlease collect this assessment item via ".$result[2].".\nThank you";
			break;
		default:
			$subject = $result[1];
			$message = "Dear Student\n\nThis is your assignment item: ".$result[1];
			break;
	}
	
	echo ">>".$recipients."<<<BR/>";
	echo ">>".$sender."<<<BR/>";
	echo ">>".$subject."<<<BR/>";
	echo ">>".$message."<<<BR/>";
	
	//send email
	if (mail($recipients, $subject, $message, $sender)) {
		header("location:assessment-email.php?message=success");
	} else {
		header("location:assessment-email.php?message=fail");
	};

 ?> 